package com.joe.weather.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

import com.joe.weather.MainActivity;
import com.joe.weather.R;
import com.joe.weather.WeatherApplication;
import com.joe.weather.tool.PreferenceUtil;
import com.joe.weather.tool.SMSUtil;
import com.joe.weather.tool.WeatherUtil;

public class SmsObserveService extends Service
{
	private static final String TAG = SmsObserveService.class.getSimpleName();

	WeatherApplication application;
	
	SmsContent smsContent;

	@Override
	public void onCreate()
	{
		super.onCreate();

		application = (WeatherApplication) getApplicationContext();
		
		smsContent = new SmsContent(new Handler());
		// 注册短信变化监听
		this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContent);
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();

		this.getContentResolver().unregisterContentObserver(smsContent);
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	class SmsContent extends ContentObserver
	{
		private Cursor cursor = null;

		public SmsContent(Handler handler)
		{
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange)
		{
			super.onChange(selfChange);
			// 读取收件箱中指定号码的短信
			cursor = getContentResolver().query(
					Uri.parse("content://sms/inbox"),
					new String[] { "_id", "thread_id", "address", "read", "body" },
					" address=? and read=? and body=?", new String[] { application.destNumber, "0", "tq" },
					"date desc");

			Log.e(TAG, "AAAAAAAAAAAA.......");
			
			if (cursor != null && (cursor.getCount()>0))
			{
				
				/*// 更新当前未读短信状态为已读
				ContentValues cv = new ContentValues();
				cv.put("read", "1");
				cursor.moveToFirst();
				while (cursor.isLast())
				{
					getContentResolver().update(Uri.parse("content://sms/inbox"), 
							cv, " _id=?",	new String[] { "" + cursor.getInt(0) });
					cursor.moveToNext();
				}*/
				
				
				// 删除当前短信 
				cursor.moveToFirst();
				while (cursor.isLast())
				{
			        String pid = cursor.getString(1);  //Get thread id; 
			        String uri = "content://sms/conversations/" + pid; 
			        
					getContentResolver().delete(Uri.parse(uri), 
							" _id=?",	new String[] { "" + cursor.getInt(0) });
					
					cursor.moveToNext();
				}
				
				sendWeatherSMS();
			}
			Log.e(TAG, "BBBBBBBBBBBBBBBBBBBBBBBB....");
		}
	}
	
	private void sendWeatherSMS()
	{
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		boolean smsFuncSwitch = sp.getBoolean("smsFuncSwitch", true);
		if(smsFuncSwitch)
		{
			String currentCityCode = sp.getString("cityName", "101280101");
			
			PreferenceUtil preUtil = new PreferenceUtil(this);
			String callName = preUtil.getCurrentCallName();
			String cityName = preUtil.getCurrentCityName(currentCityCode);
			
			String smsDest = sp.getString(application.CELLPHONE_NUMBER, application.destNumber);
			String smsContent = WeatherUtil.getSMSMessage(callName, currentCityCode, cityName);
			
			if(!"".equals(smsContent))
			{
				SMSUtil.sendMessage(getBaseContext(), smsDest, smsContent);
				
				showNotification(true, callName, cityName);
			}
			else
			{
				showNotification(false, callName, cityName);
			}
		}
	}

	private void showNotification(boolean successFlag, String callName, String cityName)
	{
		NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
		Notification notification = new Notification(R.drawable.weather, "Hello,there!", System.currentTimeMillis()); 
		notification.defaults = Notification.DEFAULT_ALL;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent(this.getBaseContext(), MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 
		PendingIntent contentIntent = PendingIntent.getActivity(
				getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		if(successFlag)
		{
			notification.setLatestEventInfo(getBaseContext(), "成功！", "给猪头发送天气预报--成功！", contentIntent);
		}
		else
		{
			notification.setLatestEventInfo(getBaseContext(), "失败！", "给猪头发送天气预报--失败！", contentIntent);
		}
		manager.notify(0, notification);
	}
}
